const router = require('koa-router')()
const { exec } = require('../db/index')

router.prefix('/api') // 前缀

// const db = []

router.get('/user', async (ctx, next) => {
  let data = await exec(`select * from users`)
  ctx.body = data
})

// add
router.post('/user', async (ctx, next) => {
  const { username, password, nickname } = ctx.request.body;
  // 添加不重复数据 1. 查询 看是否存在
  let list = await exec(`select * from users where username=?`, [username])
  if (!list.length) {
    let data = await exec(`
    insert into users (username, password, nickname) values (?,?,?)`,
      [username, password, nickname]);
    ctx.body = { code: 0, msg: 'success', id: data.insertId };
  } else {
    ctx.body = {
      code: -1,
      msg: '数据已经存在了'
    };
  }
})

// 修改逻辑
router.put('/user/:id', async (ctx, next) => {
  const id = ctx.params.id;
  const { username, password, nickname } = ctx.request.body;
  let data = await exec(`update users set username=? , password=?, nickname=? where id = ?`, [username, password, nickname, id])
  if (data.affectedRows) {
    ctx.body = { code: 1, msg: 'success', affectedRows: data.affectedRows }
  } else {
    ctx.body = { code: -1, msg: '更新失败' }
  }
})

//  
router.delete('/user/:id', async (ctx, next) => {
  const id = ctx.params.id
  const data = await exec(`delete from users where id=?`, [id])
  if (data.affectedRows) {
    ctx.body = { code: 1, msg: 'success', affectedRows: data.affectedRows }
  } else {
    ctx.body = { code: -1, msg: '删除失败' }
  }
})



module.exports = router
